@let activeEnvironment = activeEnvironment$ | async;
@let environments =
  { local: environments$ | async, cloud: cloudEnvironments$ | async };
@let environmentsStatus = environmentsStatus$ | async;
@let isCloudEnabled = isCloudEnabled$ | async;
@let isConnected = isConnected$ | async;
@let categories = categories$ | async;
@let sync = sync$ | async;
@let syncAlert = syncAlert$ | async;
@let settings = settings$ | async;
@let instances = instances$ | async;
@let user = user$ | async;
@let localDropdownMenuItems = localDropdownMenuItems$ | async;
@let deployInstances = deployInstances$ | async;
@let instanceUrls = instanceUrls$ | async;

<div
  class="environments-menu d-flex flex-column h-100"
  appTourStep="tour-environments-menu"
>
  @for (
    category of categories;
    track category.id;
    let isFirst = $first;
    let isLast = $last
  ) {
    <div
      class="d-flex flex-column overflow-hidden"
      [ngStyle]="{
        flex: category.collapsed ? '0 0 min-content' : 1
      }"
      [ngClass]="{
        'border-bottom': (category.collapsed && !isLast) || !isLast
      }"
    >
      <div
        class="d-flex align-items-center p-2"
        appDraggable
        appDropzone
        dragContainer="environmentCategories"
        [dragEnabled]="dragEnabled"
        dragParentId="root"
        [dragIsContainer]="false"
        [dragId]="category.id"
        (dropped)="reorganizeEnvironmentsCategories($event)"
      >
        <div class="d-flex align-items-center mw0">
          @if (category.id === 'cloud') {
            <button
              type="button"
              class="btn btn-link btn-icon btn-sm p-0"
              [ngClass]="{
                'text-danger':
                  (!user || user.plan === 'FREE' || !sync.status) &&
                  environments.cloud.length > 0,
                'text-warning':
                  (!user || user.plan === 'FREE' || !sync.status) &&
                  environments.cloud.length === 0,
                'cursor-pointer': !user || user.plan === 'FREE' || !sync.status,
                'cursor-default': user && user.plan !== 'FREE' && sync.status
              }"
              (click)="cloudReconnect()"
            >
              <ng-template #cloudIconTooltip>
                @if (!sync.status) {
                  @if (sync.offlineReason) {
                    Disconnected: {{ offlineReasonsLabels[sync.offlineReason] }}
                  } @else if (!user) {
                    Disconnected: not logged in
                  } @else if (user.plan === 'FREE') {
                    Disconnected: free plan
                  } @else {
                    Disconnected: please check your internet connection and your
                    credentials. Click to try to reconnect.
                  }
                } @else {
                  Connected: quota {{ environments.cloud.length }}/{{
                    user?.cloudSyncItemsQuota
                  }}
                }
              </ng-template>
              <app-svg
                [icon]="
                  user && user.plan !== 'FREE' && sync.status
                    ? 'cloud'
                    : 'cloud_off'
                "
                [ngbTooltip]="category.id === 'cloud' ? cloudIconTooltip : null"
                class="pe-2"
              ></app-svg>
            </button>
          } @else {
            <app-svg icon="computer" class="pe-2"></app-svg>
          }
          <div class="text-truncate">
            {{ category.label }}
            @if (category.id === 'cloud' && syncAlert) {
              @if (syncAlert.includes('OFFLINE_WARNING')) {
                <a
                  class="ms-2 text-warning cursor-pointer"
                  [ngbTooltip]="alertLabels[syncAlert]"
                  href="{{ offlineWarningLink }}"
                  target="_blank"
                >
                  <app-svg icon="warning"></app-svg>
                </a>
              } @else {
                <span
                  class="ms-2 text-warning"
                  [ngbTooltip]="alertLabels[syncAlert]"
                >
                  <app-svg icon="warning"></app-svg>
                </span>
              }
            }
          </div>
        </div>
        <div class="ms-auto d-flex align-items-center">
          @if (category.collapsed) {
            <span class="badge badge-hollow font-weight-bold">
              {{ environments[category.id]?.length }}
            </span>
          }
          @if (category.id === 'cloud') {
            <app-dropdown-menu
              idPrefix="cloud-environments-add"
              icon="add_box"
              [items]="cloudDropdownMenuItems"
              [iconFaded]="true"
              [noYPadding]="true"
            >
            </app-dropdown-menu>
          } @else if (category.id === 'local') {
            <app-dropdown-menu
              idPrefix="local-environments-add"
              icon="add_box"
              [items]="localDropdownMenuItems"
              [iconFaded]="true"
              [noYPadding]="true"
              [menuHeightFitContent]="true"
            >
            </app-dropdown-menu>
          }
          @if (!isWeb) {
            <button
              type="button"
              class="btn btn-link btn-icon btn-sm"
              (click)="collapseCategory(category.id, category.collapsed)"
            >
              <app-svg
                [icon]="category.collapsed ? 'unfold_more' : 'unfold_less'"
              ></app-svg>
            </button>
          }
        </div>
      </div>

      <div class="overflow-auto flex-fill" [ngbCollapse]="category.collapsed">
        <ng-container
          [ngTemplateOutlet]="environmentListTemplate"
          [ngTemplateOutletContext]="{
            isCloud: category.id === 'cloud',
            environments: environments[category.id],
            activeEnvironment: activeEnvironment,
            environmentsStatus: environmentsStatus,
            dragContainer: category.id + 'Environments'
          }"
        >
        </ng-container>
      </div>
    </div>
  }

  <div
    appResizeColumn
    type="main"
    [minWidth]="menuSize"
    [maxWidthFactor]="0.2"
    class="resize-column"
  ></div>
</div>

<ng-template
  #environmentListTemplate
  let-isCloud="isCloud"
  let-environments="environments"
  let-activeEnvironment="activeEnvironment"
  let-environmentsStatus="environmentsStatus"
  let-dragContainer="dragContainer"
>
  <ul class="nav h-100 flex-column">
    <div class="flex-fill menu-list">
      @for (environment of environments; track environment.uuid) {
        <li
          class="nav-item"
          appDraggable
          appDropzone
          [dragContainer]="dragContainer"
          [dragEnabled]="dragEnabled"
          dragParentId="root"
          [dragIsContainer]="false"
          [dragId]="environment.uuid"
          (dropped)="reorganizeEnvironments($event)"
        >
          <a
            class="nav-link d-flex pe-0 hover-parent"
            [ngClass]="{
              active: activeEnvironment?.uuid === environment.uuid
            }"
            appScrollWhenActive
            (click)="selectEnvironment(environment.uuid)"
          >
            <div
              [formGroup]="activeEnvironmentForm"
              class="d-flex flex-column mw0"
            >
              <div
                class="nav-link-label"
                [ngClass]="{
                  'text-truncate': settings.truncateRouteName,
                  'text-break': !settings.truncateRouteName
                }"
              >
                <app-editable-element
                  [text]="environment.name"
                  formControlName="name"
                  [editCondition]="activeEnvironment?.uuid === environment.uuid"
                  (editChange)="enableDrag(!$event)"
                ></app-editable-element>
              </div>

              @if (isWeb) {
                <div
                  class="nav-link-subtitle mt-1 d-flex align-items-center svg-text-align"
                >
                  <app-svg
                    class="me-2"
                    [ngClass]="{
                      'text-success':
                        instances[environment.uuid]?.status === 'RUNNING',
                      'text-muted':
                        instances[environment.uuid]?.status !== 'RUNNING'
                    }"
                    icon="cloud"
                    size="12"
                    [ngbTooltip]="
                      instances[environment.uuid]?.status === 'RUNNING'
                        ? 'Cloud instance running'
                        : 'Cloud instance stopped'
                    "
                  ></app-svg>
                  @if (environment.proxyMode) {
                    <app-svg
                      class="text-primary me-2"
                      icon="security"
                      size="12"
                      ngbTooltip="Proxy mode enabled"
                    ></app-svg>
                  }
                  @if ((logsRecording$ | async)[environment.uuid] === true) {
                    <app-svg
                      class="text-danger animation-flash me-2"
                      icon="record"
                      size="12"
                      ngbTooltip="Recording in progress"
                    ></app-svg>
                  }
                  @let webUrl =
                    instanceUrls[environment.uuid].webUrl +
                    (environment?.endpointPrefix
                      ? '/' + environment?.endpointPrefix
                      : '');
                  <span
                    class="text-truncate pe-1"
                    (click)="
                      copyUrlToClipboard(
                        environment,
                        instances[environment.uuid],
                        'webUrl',
                        $event
                      )
                    "
                    ngbTooltip="Click to copy"
                  >
                    {{ webUrl }}
                  </span>
                </div>
              } @else {
                <div
                  class="nav-link-subtitle mt-1 d-flex align-items-center svg-text-align"
                >
                  <!-- Display local server URL and status on desktop -->
                  @if (environmentsStatus[environment.uuid]) {
                    <app-svg
                      class="me-2"
                      [ngClass]="{
                        'text-success':
                          environmentsStatus[environment.uuid]?.running &&
                          !environmentsStatus[environment.uuid]?.needRestart,
                        'text-muted':
                          !environmentsStatus[environment.uuid]?.running,
                        'text-orange':
                          environmentsStatus[environment.uuid]?.needRestart
                      }"
                      icon="computer"
                      size="12"
                      [ngbTooltip]="
                        environmentsStatus[environment.uuid]?.running &&
                        !environmentsStatus[environment.uuid]?.needRestart
                          ? 'Local server running'
                          : !environmentsStatus[environment.uuid]?.running
                            ? 'Local server stopped'
                            : environmentsStatus[environment.uuid]?.needRestart
                              ? 'Local server needs restart'
                              : ''
                      "
                    ></app-svg>
                  }
                  @if (environment.tlsOptions.enabled) {
                    <app-svg
                      class="text-warning me-2"
                      icon="lock"
                      size="12"
                      ngbTooltip="TLS enabled"
                    ></app-svg>
                  }
                  @if (environment.proxyMode) {
                    <app-svg
                      class="text-primary me-2"
                      icon="security"
                      size="12"
                      ngbTooltip="Proxy mode enabled"
                    ></app-svg>
                  }
                  @if ((logsRecording$ | async)[environment.uuid] === true) {
                    <app-svg
                      class="text-danger animation-flash me-2"
                      icon="record"
                      size="12"
                      ngbTooltip="Recording in progress"
                    ></app-svg>
                  }
                  @let localUrl =
                    instanceUrls[environment.uuid].localUrl +
                    (environment?.endpointPrefix
                      ? '/' + environment?.endpointPrefix
                      : '');
                  <span
                    class="text-truncate pe-1"
                    (click)="
                      copyUrlToClipboard(
                        environment,
                        instances[environment.uuid],
                        'localUrl',
                        $event
                      )
                    "
                    ngbTooltip="Click to copy"
                  >
                    {{ localUrl }}
                  </span>
                </div>

                <!-- Display remote instance URL and status on desktop -->
                @if (instances[environment.uuid]) {
                  <div
                    class="nav-link-subtitle mt-1 d-flex align-items-center svg-text-align"
                  >
                    <app-svg
                      class="me-2"
                      [ngClass]="{
                        'text-success':
                          instances[environment.uuid]?.status === 'RUNNING',
                        'text-muted':
                          instances[environment.uuid]?.status !== 'RUNNING'
                      }"
                      icon="cloud"
                      size="12"
                      [ngbTooltip]="
                        instances[environment.uuid]?.status === 'RUNNING'
                          ? 'Cloud instance running'
                          : 'Cloud instance stopped'
                      "
                    ></app-svg>

                    @let webUrl =
                      instanceUrls[environment.uuid].webUrl +
                      (environment?.endpointPrefix
                        ? '/' + environment?.endpointPrefix
                        : '');
                    <span
                      class="text-truncate pe-1"
                      (click)="
                        copyUrlToClipboard(
                          environment,
                          instances[environment.uuid],
                          'webUrl',
                          $event
                        )
                      "
                      ngbTooltip="Click to copy"
                    >
                      {{ webUrl }}
                    </span>
                  </div>
                }
              }
            </div>
            <div
              class="ms-auto d-flex flex-column align-items-center justify-content-between"
            >
              <app-dropdown-menu
                [idPrefix]="'environment-' + environment.uuid"
                [items]="
                  isCloud
                    ? cloudEnvironmentDropdownMenuItems
                    : localEnvironmentDropdownMenuItems
                "
                [payload]="{
                  environmentUuid: environment.uuid
                }"
                [iconFaded]="true"
                [noYPadding]="true"
              ></app-dropdown-menu>
              <app-team-presence
                [presence]="sync?.presence"
                [user]="user"
                [displaySelf]="false"
                filterBy="environmentUuid"
                [filterContext]="environment.uuid"
                size="16"
                [showTooltipList]="false"
              ></app-team-presence>
            </div>
          </a>
        </li>
      } @empty {
        @if (isCloud) {
          @if (isCloudEnabled) {
            <div class="message message-sm m-2">No cloud environment</div>
          } @else {
            <div class="message message-sm m-2">
              @if (!isConnected) {
                <a href="#" (click)="login($event)">Log in</a> or
              }
              <a [href]="cloudPlansURL" target="_blank"
                >Subscribe to Mockoon Cloud</a
              >
              to create and deploy cloud environments
            </div>
          }
        } @else {
          <div class="message message-sm m-2">No local environment</div>
        }
      }
    </div>

    @if (isCloud && isCloudEnabled) {
      <li class="nav-item" (click)="openManageInstancesModal()">
        <a class="nav-link border-top mt-auto text-truncate">
          <small>
            <app-svg class="pe-2" icon="server_settings"></app-svg>
            {{ deployInstances.length }}&nbsp;
            {{ deployInstances.length > 1 ? 'instances' : 'instance' }}
            running
          </small>
        </a>
      </li>
    }
  </ul>
</ng-template>
